#include <stdio.h>
#include "apictrl.h"

#ifdef _DEBUG
#define THIS_BUILD "debug"
#else
#define THIS_BUILD "release"
#endif


CAPICtrl g_stCtrl;

void PrintUsage(const char* s)
{
    printf("%s   \t run program\n", s);
    printf("%s -g\t run program not daemon\n", s);
    printf("%s -h\t show help\n", s);
    printf("%s -v\t show version\n", s);
    printf("%s -u\t do not reload data in shm\n", s);
}

void PrintVersion()
{
    printf("huochao webgame apisvr %s %s version build at %s %s\n", 
#ifdef  THIS_VERSION
        THIS_VERSION
#else
        "unknown"
#endif
        , THIS_BUILD, __DATE__, __TIME__);
}

void AtExit()
{
    CTServerUtils::RemovePidFile(APPNAME);
}

int main(int argc, char** argv)
{
    int iRet = 0;
    bool bDaemon = true;	// 默认后台执行
    bool bResetShm = true;  

    int iOpt = 0;
    while ((iOpt = getopt(argc, argv, "vghu")) != -1)
    {
        switch(iOpt)
        {
        case 'v':
            PrintVersion();
            return 0;

        case 'g':
            bDaemon = false;
            break;

        case 'u':
            bResetShm = false;
            break;

        case 'h':
            PrintUsage(argv[0]);
            return 0;
        }
    }

    // 后台运行
    if (bDaemon)
    {
        CTServerUtils::InitDaemon();
    }

    // 避免启动多个进程
    if (!CTServerUtils::CheckSingleRun(argv[0]))
    {
        return -1;
    }

    // 退出时自动清理
    atexit(AtExit);

    try
    {
        if (false == bResetShm)
        {
            g_stCtrl.DoNotResetShm();
        }

        iRet = g_stCtrl.Init();
        CHECK_RETURN(iRet);

        iRet = g_stCtrl.Run();
        CHECK_RETURN(iRet);

        iRet = g_stCtrl.Exit();
        CHECK_RETURN(iRet);
    }
    catch (CTException& e)
    {
        CT_ERROR(("except: %s", e.GetErrorMsg()));
        return -1;
    }

    return 0;
}
